package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.log.KiteLogger;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.InfServContextDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.ExtOrderInfoCache;
import com.iwhalecloud.bss.kite.cucc.service.pos.bo.KitePosSceneBO;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosServiceHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("cuccPosServiceHandler")
public class KitePosServiceHandler implements IKitePosServiceHandler {

	@Override
    @KiteLogger(isWrite = true)
	public KitePosDTO deal(String sceneInstId, String staffId, String orgId, CuccContextCustDTO custDto, Boolean checkAccountModule, Boolean checkContractModule, String opType) {
		// 1.初始化转单业务场景对象
		KitePosHandlerContext context = initContext(sceneInstId, staffId, orgId, custDto, checkAccountModule, checkContractModule, null, opType);
		this.handle(context);
        CuccPosServiceUtils.replaceGoodsInstanceId(sceneInstId, context.getPosDto());
        return context.getPosDto();
	}
    @Override
    public KitePosDTO deal(InfServContextDTO context) {
        // 1.初始化转单业务场景对象
        KitePosHandlerContext posContext = initContext(context.getSceneInstId(), context.getStaffId(),
            context.getOrgId(), context.getCustDto(), context.getCheckAccountModule(), context.getCheckContractModule(), context.getOfferInstId(), null);
        this.handle(posContext);
        return posContext.getPosDto();
    }

    private KitePosHandlerContext initContext(String sceneInstId, String staffId, String orgId,
        CuccContextCustDTO custDto, Boolean checkAccountModule, Boolean checkContractModule, String offerInstId, String opType) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
	    KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
	    KitePosSceneBO posSceneBO = new KitePosSceneBO();
        posSceneBO.setCartId(kiteSceneInst.getCartId());
		posSceneBO.setCustId(custDto.getCustId());
        posSceneBO.initPosData(sceneInstId, offerInstId);

		KitePosHandlerContext context = new KitePosHandlerContext();
		context.setCheckAccountModule(checkAccountModule);
		context.setCheckContractModule(checkContractModule);
		context.setSceneInstId(sceneInstId);
		context.setStaffId(staffId);
		context.setOrgId(orgId);
		context.setLanId(custDto.getLanId());
		context.setCustId(custDto.getCustId());
		context.setCustDto(this.initCustInfo(custDto));
        context.setOfferInstId(offerInstId);
        // 操作类型:URGENT（加急）、POSTPONE（延期）、LOCK（挂起）、RELEASE（解挂）、ALTER（追单）、CANCEL（退单）
        context.setOpType(opType);
        if (ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())) {
            context.setNewCustDto(CuccPosServiceUtils.queryNewCustInfo(kiteSceneInst.getNewCustId()));
        }
		context.setPosSceneBO(posSceneBO);
        // 设置下单流程标识
        this.setBcmcFlow(context);
		//从缓存取，签订和变更场景
		context.setPosDto(ExtOrderInfoCache.get(sceneInstId));
		initPosHandlers(context);
		return context;
	}

	/**
	 * 上下文中取信息不全，重新取一次
	 * @param custId
	 * @return
	 */
	private CuccContextCustDTO initCustInfo(CuccContextCustDTO custDto) {
	    ICustReceptionService custReceptionService = SpringUtil.getBean(ICustReceptionService.class);
	    CuccContextCustDTO contextCust = new CuccContextCustDTO();
        CuccCustInfoDetailDTO cuccCustInfoDTO = custReceptionService.getCustomerInfoNew(custDto.getCustId());
        if (Objects.nonNull(cuccCustInfoDTO)) {
            KiteBeanUtils.copyProperties(cuccCustInfoDTO, contextCust);
            contextCust.setProvinceCode(cuccCustInfoDTO.getProvinceCode());
            contextCust.setCustName(cuccCustInfoDTO.getCustName());
            contextCust.setLanId(cuccCustInfoDTO.getCityCode());
            contextCust.setRegionId(cuccCustInfoDTO.getBcityCode());
            contextCust.setCustType(cuccCustInfoDTO.getCustClassType());
            contextCust.setBbssCustId(cuccCustInfoDTO.getBbssCustId());
            contextCust.setCbssId(cuccCustInfoDTO.getCustId());
            contextCust.setAttrs(cuccCustInfoDTO.getAttrs());
            contextCust.setCustStatus(custDto.getCustStatus());
        }
        return contextCust;
	}

    // 设置订单受理流程
    private void setBcmcFlow(KitePosHandlerContext context) {
        // 默认不是BCMC流程
        context.setIsBcmcFlow(Boolean.FALSE);

        // 获取场景中受理根商品实例
        KiteOfferInst offerInst = CuccPosServiceUtils.getRootOfferInst(context.getSceneInstId(),
            context.getCustDto().getCustId());
        if (Objects.nonNull(offerInst)) {
            // 判断商品分类是否属于配置中
            if (CuccPosServiceUtils.checkBcmcGoodsCategroy(offerInst.getOfferId())) {
                context.setIsBcmcFlow(Boolean.TRUE);
            }
        }
    }

	private void initPosHandlers(KitePosHandlerContext context) {
		List<IKitePosSceneHandler> posHandlers = new ArrayList<>();
		posHandlers.add(SpringUtil.getBean(KitePosAcceptStaffHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosRequestHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosCustomerHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosDeveloperHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosOperatorHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosAgentHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosLinkmanHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosOrderHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosUserHandler.class));
        posHandlers.add(SpringUtil.getBean(KitePosMemUserHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosGroupsHandler.class));
		//以下handler根据服务提供设置
		posHandlers.add(SpringUtil.getBean(KitePosPaymentHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosDiscountHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosAccountHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosContractHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosDeliveryHandler.class));

		//最后封装商品节点
		posHandlers.add(SpringUtil.getBean(KitePosGoodsHandler.class));
        posHandlers.add(SpringUtil.getBean(KitePosRelationHandler.class));
        posHandlers.add(SpringUtil.getBean(KitePosMemRelationHandler.class));
		posHandlers.add(SpringUtil.getBean(KitePosTransferPlanHandler.class));
        posHandlers.add(SpringUtil.getBean(KitePosBatchAcceptHandler.class));
		//posHandlers.add(SpringUtil.getBean(KitePosInstanceIdHandler.class));
		context.setPosHandlers(posHandlers);
	}

	private void handle(KitePosHandlerContext context) {
		context.getPosHandlers().forEach((handler) -> {
			handler.handle(context);
		});
	}

}
